package com.dc.juc.example._11_lock;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Description: ReentrantReadWriteLock  读写锁
 *
 *  读写锁,它表示两个锁，一个是读操作相关的锁，称为共享锁；一个是写相关的锁，称为排他锁。
 *
 * @author: gdc
 * @date: 2021/8/16
 * @version 1.0
 */
public class _3_ReentrantReadWriteLock {

    /**
     * 存放数据
     */
    private final Map<String, String> map = Maps.newTreeMap();

    /**
     * 读写锁
     */
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    /**
     * 获取读锁
     */
    private final Lock readLock = lock.readLock();
    /**
     * 获取写锁
     */
    private final Lock writeLock = lock.writeLock();

    /**
     * 获取值，使用读锁进行加锁
     */
    public String get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    /***
     * 获取所有key，使用读锁进行加锁
     */
    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    /**
     * 存放值，使用写锁进行加锁
     */
    public void put(String key, String value) {
        writeLock.lock();
        try {
            map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

}
